<template>
  <div class="todo-container">
    <div class="todo-warp">
        <Header :todoAdd="todoAdd"/>
        <List :todos="todos"/>
        <Footer :todos="todos" :checkAll="checkAll" :clearData="clearData"/>
    </div>
  </div>
</template>
<script lang="ts">
  import {defineComponent, onMounted, provide, reactive, toRefs,watch} from 'vue'
  import Header from './components/header.vue'
  import List from './components/list.vue'
  import Footer from './components/footer.vue'
  import {Todo} from './types/todo'
  import {saveTods,readTodos} from './utils/localStrorageUtils'
  export default defineComponent({
    name:'App',
    components:{
      Header,
      List,
      Footer
    },
    
    setup(){
        const state = reactive<{todos:Todo[]}>({
          // todos:[{
          //     id:1,
          //     title:'奔驰',
          //     isChecked:false
          // },
          // {
          //     id:2,
          //     title:'宝马',
          //     isChecked:true
          // },
          // {
          //     id:3,
          //     title:'宾利',
          //     isChecked:false
          // }]
          todos:[]
       })
       onMounted(()=>{
          setTimeout(()=>{
            state.todos=readTodos()
          },1000)
       })
       
      //  添加数据的方法
        const todoAdd = (todo:Todo)=>{
          state.todos.unshift(todo)
        }
        // 删除数据
        const deleteData = (index:number)=>{
          state.todos.splice(index,1)
        }
        //复选框更新数据
        const updateData = (todo:Todo,isComplete:boolean)=>{
          todo.isChecked=isComplete
          // 更新后的数据
            console.log(todo); 
        }
        // provide传递函数方法
        provide('deleteData',deleteData)
        provide('updateData',updateData)
        // 全选全不选
        const checkAll = (isChecked:boolean)=>{
          state.todos.forEach((todo)=>{
              todo.isChecked=isChecked
          })
        }
        // 清理选中数据
        const clearData = ()=>{
          state.todos=state.todos.filter(todo=>!todo.isChecked)
        }
        // 监视todos数组的变化
        // watch(()=>state.todos,(value)=>{
        //   // 保存到浏览器缓存中
        //    saveTods(value)
        // },{deep:true})
        watch(()=>state.todos,saveTods,{deep:true})
       return {
        ...toRefs(state),
        todoAdd,
        deleteData,
        updateData,
        checkAll,
        clearData
       }
    }
    
  })
</script>
<style scoped lang="less">
  .todo-container{
    width: 600px;
    margin: 0 auto;
    .todo-warp{
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
    }
  }
</style>